/**
 * 文件上传相关API
 */
import setting from "../config.js";

const http = uni.$u.http;

const fileApi = {
	// 单张图片上传
	uploadFile: url => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: setting.PRO_URL + '/infra/file/upload',
				filePath: url,
				name: 'file',
				success: (res) => {
					const data = JSON.parse(res.data);
					if (data.code == 0) {
						resolve(data.data)
					}
					reject('系统异常');
				},
				fail: (err) => {
					reject(err);
				}
			});
		})
	},

	// 批量上传图片
	uploadFiles: (tempFilePaths, options = {}) => {
		const { showLoading = true, loadingText = '上传中...' } = options;

		return new Promise((resolve, reject) => {
			if (showLoading) {
				uni.showLoading({
					title: loadingText,
					mask: true
				});
			}

			const uploadPromises = tempFilePaths.map(filePath => {
				return fileApi.uploadFile(filePath)
					.catch(err => {
						uni.showToast({
							title: '图片上传失败',
							icon: 'none'
						});
						return Promise.reject(err);
					});
			});

			Promise.all(uploadPromises)
				.then(resolve)
				.catch(reject)
				.finally(() => {
					if (showLoading) {
						uni.hideLoading();
					}
				});
		});
	}
}

export default fileApi